package com.mallcai.bigdata.ladon.service.export.impl;

import com.mallcai.bigdata.ladon.client.export.ExportStrategy;
import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;

/**
 * described :
 *
 * @author CaKeDou
 * @date 2019-09-25 17:42
 * Modify:
 */
public class ExportContext<T> {

    private final ExportPipeline pipeline;

    private int currentIndex = 0;

    /**
     * 是否完成,如果已经完成,则后面所有的handler都不会继续处理
     */
    private boolean isCompleted = false;

    private String fileName;

    private static final String ROOT_FILE_PATH = "/tmp/ladonfiles/";

    private ExportStrategy exportStrategy;

    /**
     * 原始数据
     */
    private T oriData;

    /**
     * 目标数据
     */
    private ReportDataVO targetData;

    /**
     * 下载地址
     */
    private String downloadUrl;

    public ExportContext(ExportPipeline pipeline, String fileName, T oriData, ExportStrategy exportStrategy) {
        this.pipeline = pipeline;
        this.fileName = fileName;
        this.oriData = oriData;
        this.exportStrategy = exportStrategy;
    }

    public void next() {
        int size = this.pipeline.getExportHandlerList().size();
        //未完成时,只要有前置拦截器,按Order从小到大顺序依次执行
        while (currentIndex < size && !isCompleted) {
            IExportHandler iExportHandler = this.pipeline.getExportHandlerList().get(currentIndex++);
            if (iExportHandler instanceof IExportPreHandler) {
                ((IExportPreHandler) iExportHandler).preHandle(this);
                break;
            }
        }
        //完成后,按Order从大到小顺序依次检查后置拦截器执行
        while (currentIndex > 0 && isCompleted) {
            if (currentIndex == size) {
                currentIndex--;
            }
            IExportHandler iExportHandler = this.pipeline.getExportHandlerList().get(currentIndex--);
            if (iExportHandler instanceof IExportPostHandler) {
                ((IExportPostHandler) iExportHandler).postHandle(this);
                break;
            }
        }

    }

    public String getFileName() {
        return fileName;
    }

    public ExportStrategy getExportStrategy() {
        return exportStrategy;
    }

    public T getOriData() {
        return oriData;
    }

    public ReportDataVO getTargetData() {
        return targetData;
    }

    public void setTargetData(ReportDataVO targetData) {
        this.targetData = targetData;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public void setCompleted(boolean completed) {
        isCompleted = completed;
    }

    public String getFilePath() {
        return ROOT_FILE_PATH + fileName;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }
}
